<template>
  <el-dialog width="60%" :title="dialogTitle" v-model="dialogVisible" modal @close="closeDialog" draggable
    :close-on-click-modal="false" :append-to-body="true">
    <el-tabs ref="tabs" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="读写器" name="reader">
        <el-form class="dialog-form" :model="formData" ref="readerForm" label-position="right" label-width="100px"
          size="medium" @submit.native.prevent>
          <el-form-item label="读写器:" prop="deviceId">
            <el-select v-model="formData.deviceId" placeholder="请选择读写器" class="full-width-input" clearable
              @change="changeReader">
              <el-option v-for="(item, index) in readerOptions" :key="index" :label="item.label" :value="item.value"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="读写器状态:" prop="state">
            <el-tag :type="formData.state === '正常' ? 'success' : 'danger'">{{
              formData.state
            }}</el-tag>
            <el-button type="primary" size="mini" style="margin-left: 10px;"
              @click="reconnect('reader')">重新连接</el-button>

          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="打印机" name="printer">
        <el-row>
          <el-col :span="20">
            <el-form class="dialog-form" :model="printerFormData" ref="readerForm" label-position="right"
              label-width="100px" size="medium" @submit.native.prevent>
              <el-form-item label="打印机:" prop="deviceId">
                <el-select v-model="printerFormData.deviceId" placeholder="请选择打印机" class="full-width-input" clearable>
                  <el-option v-for="(item, index) in printerOptions" :key="index" :label="item.deviceName"
                    :value="item.deviceId" :disabled="item.disabledFlag != 0" @click.native="changePrinter(item)">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="打印机状态:" prop="state">
                    <el-tag :type="printerFormData.state ? 'success' : 'danger'">{{
                      printerFormData.state ? '正常' : '离线'
                    }}</el-tag>
                    <el-button type="primary" size="mini" style="margin-left: 10px;"
                      @click="reconnect('printer')">重新连接</el-button>
                  </el-form-item>

                </el-col>
                <el-col :span="12">
                  <el-form-item label="模版设置:" prop="state">
                    <el-radio-group v-model="printerFormData.templateSet">
                      <el-radio :label="0">横版</el-radio>
                      <el-radio :label="1">竖版</el-radio>
                      <el-radio :label="2">方正版</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
          <el-col :span="4">
            <el-button style="float: right; width: 90px; height: 90px" type="primary"
              @click="printeTable">打印</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-table :data="tableData" border style="width: 100%" height="30vh" :row-class-name="tableRowClassName">
      <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
        :width="item.width">
      </el-table-column>
      <el-table-column label="操作" min-width="60">
        <template slot-scope="{ row }">
          <el-button v-if="activeName === 'reader'" link size="mini" @click="getRfid(row)">读卡</el-button>
          <el-popconfirm class="button10Left" title="确定要删除吗？" @confirm="() => handleDel(row)">
            <el-button slot="reference" icon="el-icon-delete" link size="mini" class="danger_button">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { dropDown, getInfo } from '@/api/bas/rfidReader'
import {
  dropDown as dropDownPrinter,
  getInfo as getPrinterInfo,
  deviceRfidPrinterlist,
} from '@/api/bas/printer'
import { batchRegister } from '@/api/rfid/label'
import { batchRegister as positionRegister } from '@/api/rfid/position'
import axios from 'axios'
import { ElNotification } from 'element-plus'


import { initWebSocket, printTableData } from '@/utils/prints'
import createRrfidNumber from '@/utils/CreateRrfidNumber'
export default {
  name: 'sendTagsDialog',
  props: {
    field: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      type: '',
      activeName: 'reader',
      dialogTitle: '',
      dialogVisible: false,
      formData: {
        deviceId: '',
        state: '未选择读写器',
        rfid: '',
      },
      tableData: [],
      tableProps: [],
      readerInfo: {},
      readerOptions: [],
      printerFormData: {
        deviceId: '',
        state: false,
        templateSet: 0,
      },
      printerInfo: {},
      printerOptions: [],
      ws: null,
    }
  },
  watch: {
    field(newv) {
      this.printerFormData.templateSet = newv.templateStyle
    },
  },
  methods: {

    reconnect(flag) {
      if (flag === 'reader') {
        this.changeReader(this.formData.deviceId)
      } else {
        this.changePrinter(this.printerFormData.deviceId)
      }
    },
    async printeTable() {
      for (const item of this.tableData) {
        item.rfid = createRrfidNumber(1) // 添加rfid属性
        // try {

        // 这里可以执行连接成功后的操作
        printTableData(item, this.printerFormData.templateSet, this.field.fields)

        await new Promise((resolve) => setTimeout(resolve, 2000)) // 暂停1秒
      }
    },
    handleClick(tab, event) {
      if (tab.name === 'reader') {
        this.$refs['readerForm'].resetFields()
      } else if (tab.name === 'printer') {
        this.$refs['readerForm'].resetFields()
      }
    },
    getReader() {
      dropDown()
        .then((res) => {
          if (res.data.code === 200) {
            this.readerOptions = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    getPrinter() {
      deviceRfidPrinterlist()
        .then((res) => {
          if (res.data.code === 200) {
            this.printerOptions = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    add(record, type) {
      this.type = type
      this.getReader()
      this.getPrinter()
      if (type === 'box') {
        this.tableProps = [
          { title: '盒号', prop: 'boxNo', width: '', checked: true },
          { title: '盒名', prop: 'boxName', width: '', checked: true },
          { title: 'RFID', prop: 'rfid', width: '', checked: true },
          { title: '盒宽(CM)', prop: 'boxWidth', width: '', checked: true },
        ]
      } else if (type === 'archive') {
        this.tableProps = [
          { title: '档号', prop: 'archiveNo', width: '', checked: true },
          { title: '题名', prop: 'archiveName', width: '', checked: true },
          { title: 'RFID', prop: 'rfid', width: '', checked: true },
          { title: '页数', prop: 'pageNo', width: '', checked: true },
        ]
      } else if (type === 'shelf') {
        this.tableProps = [
          { title: '库位名称', prop: 'positionName', width: '', checked: true },
          { title: '库位编号', prop: 'positionId', width: '', checked: true },
          { title: 'RFID', prop: 'rfid', width: '', checked: true },
        ]
      }
      this.tableData = JSON.parse(JSON.stringify(record))
      this.dialogTitle = 'RFID标签注册'
      this.dialogVisible = true
    },
    changeReader(value) {
      this.formData.rfid = ''
      getInfo(value)
        .then((res) => {
          if (res.data.code === 200) {
            this.readerInfo = res.data.data
            this.takeOn(res.data.data.deviceIp, res.data.data.devicePort)
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    changePrinter(value) {
      initWebSocket(value.deviceIp)
        .then((ws) => {
          // 这里可以执行连接成功后的操作
          if (ws) {
            this.printerFormData.state = true
          }
        })
        .catch((error) => {
          console.error('WebSocket连接失败或不支持:', error.message)
          // 这里可以处理连接失败的情况
        })
      // websocketonmessage()
      // if (initWebSocket()) {
      // } else {
      // }

      // getPrinterInfo(value)
      //   .then((res) => {
      //     if (res.data.code === 200) {
      //       this.printerInfo = res.data.data
      //       // 连接websocket
      //     } else {
      //       this.$message.error(res.data.message)
      //     }
      //   })
      //   .catch((err) => {
      //     this.$message.error(err)
      //   })
    },
    takeOn(ip, port) {
      const that = this
      let url = 'http://' + ip + ':' + port + '/takeon'
      axios
        .get(url, { timeout: 10000 })
        .then((res) => {
          if (res.data.search('ok') !== -1) {
            that.formData.state = '正常'
          } else {
            that.formData.state = '离线'
          }
        })
        .catch((error) => {
          that.formData.state = '离线'
          this.$message.warning('连接失败')
        })
    },
    getRfidData(callback, retryCount = 0) {
      const maxRetries = 5 // 最大重试次数
      const url = `http://${this.readerInfo.deviceIp}:${this.readerInfo.devicePort}/getrfid/?deviceType=${this.readerInfo.deviceType}`

      axios
        .get(url, { timeout: 1000 })
        .then((res) => {
          const rfidData = eval('(' + res.data + ')').result

          if (rfidData.length === 0) {
            // 没有获取到数据
            if (retryCount < maxRetries) {
              // 重试获取数据
              setTimeout(() => {
                this.getRfidData(callback, retryCount + 1, this.readerInfo.deviceType) // 重试获取数据
              }, 1000) // 1秒后重试
            } else {
              // 达到最大重试次数
              ElNotification({
                message: '未能获取到标签，请检查设备',
                type: 'warning',
              })
              this.takeOff()

            }
          } else if (rfidData.length > 1) {
            ElNotification({
              message: '只能放置一个标签',
              type: 'warning',
            })
          } else {
            // 只有一个标签时，获取其ID
            const rfidId = rfidData[0].ID

            // 查询数据库是否有使用此标签
            callback(rfidId)
          }
        })
        .catch((error) => {
          this.$message.warning('连接失败')
        })
    },
    getRfid(row) {
      const that = this
      if (that.formData.state === '正常') {
        // 进行开启读写器
        this.takeOn(this.readerInfo.deviceIp, this.readerInfo.devicePort)

        // 开始读取
        this.getRfidData((rfidId) => {
          that.formData.rfid = rfidId
          that.tableData.forEach((item, index) => {
            if (item.labelId === row.labelId) {
              item.rfid = rfidId
              // that.tableRowClassName({item, index})
            }
          })

          this.takeOff()
        })
      } else if (that.formData.state === '离线') {
        ElNotification({
          message: '读写器离线',
          type: 'warning',
        })
      } else {
        ElNotification({
          message: '请选择读写器',
          type: 'warning',
        })
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.rfid) {
        return 'success-row'
      }
    },
    takeOff() {
      const that = this
      let url = 'http://' + that.readerInfo.deviceIp + ':' + that.readerInfo.devicePort + '/takeoff'
      axios
        .get(url, { timeout: 1000 })
        .then((res) => {
          if (res.data.search('ok') !== -1) {
            // this.$message.warning('关闭连接')

          }
        })
        .catch((error) => {
          this.$message.warning('连接失败')
        })
    },
    handleDel(row) {
      this.tableData = this.tableData.filter((item) => item.labelId !== row.labelId)
    },
    submitForm() {
      // 判断表格中是否还有数据
      if (this.tableData.length === 0) {
        this.$message.warning('注册列表不能为空')
        return
      }
      // 将表格中的rfid值拿出来
      const rfidArr = this.tableData.map((item) => item.rfid)
      if (rfidArr.includes('') || rfidArr.includes(null)) {
        this.$message.warning('注册列表中RFID不能为空')
        return
      }
      // 判断列表中的rfid是否有重复的
      if (
        this.tableData.some((item, index, arr) => {
          return arr.indexOf(item) !== index
        })
      ) {
        this.$message.warning('注册列表中RFID不能重复')
        return
      }
      if (this.type === 'shelf') {
        positionRegister(this.tableData)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success('注册成功')
              this.closeDialog()
              this.$emit('ok')
            } else {
              this.$message.warning(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
      } else {
        batchRegister(this.tableData)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success('注册成功')
              this.closeDialog()
              this.$emit('ok')
            } else {
              this.$message.warning(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
      }
    },
    closeDialog() {
      if (this.formData.state === '正常') {
        this.takeOff()
      }
      // this.$refs['readerForm'].resetFields()

      this.dialogVisible = false
      // this.$refs.tabs.$destroy()
    },
  },
}
</script>

<style scoped lang="less">
.el-table .success-row {
  background: #f0f9eb;
}
</style>
